package com.lei.springbootpractice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lei.springbootpractice.dao.ConversationDao;
import com.lei.springbootpractice.dao.ConsoleDao;
import com.lei.springbootpractice.pojo.ConversationPojo;
import com.lei.springbootpractice.pojo.ConsolePojo;
import com.lei.springbootpractice.pojo.UserPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

@Service
public class ConversationService {
    
    @Autowired
    private ConversationDao conversationDao;
    
    @Autowired
    private ConsoleDao consoleDao;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private NotificationService notificationService;
    
    /**
     * 智能选择客服
     * 根据当前活跃对话数量选择负载最少的客服
     */
    public String selectCustomerService() {
        List<UserPojo> customerServices = userService.getCustomerServices();
        if (customerServices.isEmpty()) {
            return null;
        }
        
        // 如果只有一个客服，直接返回
        if (customerServices.size() == 1) {
            return customerServices.get(0).getUserID();
        }
        
        // 计算每个客服的活跃对话数量，选择负载最少的
        String selectedServiceId = null;
        int minConversations = Integer.MAX_VALUE;
        
        for (UserPojo service : customerServices) {
            QueryWrapper<ConversationPojo> wrapper = new QueryWrapper<>();
            wrapper.eq("customer_service_id", service.getUserID())
                   .eq("status", "active");
            
            Long count = conversationDao.selectCount(wrapper);
            int conversationCount = count.intValue();
            
            if (conversationCount < minConversations) {
                minConversations = conversationCount;
                selectedServiceId = service.getUserID();
            }
        }
        
        // 如果负载相同，随机选择
        if (selectedServiceId == null) {
            Random random = new Random();
            selectedServiceId = customerServices.get(random.nextInt(customerServices.size())).getUserID();
        }
        
        return selectedServiceId;
    }
    
    /**
     * 开始新对话
     * 如果顾客已有活跃对话，则关闭旧对话并删除聊天记录，创建新对话
     */
    @Transactional
    public ConversationPojo startNewConversation(String customerId) {
        // 1. 检查是否有现有的活跃对话
        ConversationPojo existingConversation = getActiveConversationByCustomer(customerId);
        
        if (existingConversation != null) {
            // 2. 关闭旧对话并删除聊天记录
            closeConversationAndDeleteMessages(existingConversation.getConversationId());
        }
        
        // 3. 选择客服
        String customerServiceId = selectCustomerService();
        if (customerServiceId == null) {
            throw new RuntimeException("暂无客服在线");
        }
        
        // 4. 创建新对话
        ConversationPojo conversation = new ConversationPojo();
        conversation.setCustomerId(customerId);
        conversation.setCustomerServiceId(customerServiceId);
        conversation.setStatus("active");
        
        conversationDao.insert(conversation);
        
        // 5. 创建通知给客服
        UserPojo customer = userService.getUserByUserID(customerId);
        String customerName = customer != null ? customer.getUserName() : "用户";
        notificationService.createNotification(
            customerServiceId,
            "customer_service",
            "conversation_started",
            conversation.getConversationId(),
            "发起了新的客服咨询",
            customerName
        );
        
        return conversation;
    }
    
    /**
     * 与指定客服开始新对话
     * 如果顾客已有活跃对话，则关闭旧对话并删除聊天记录，创建新对话
     */
    @Transactional
    public ConversationPojo startConversationWithSpecificService(String customerId, String customerServiceId) {
        // 1. 验证客服是否存在且角色正确
        List<UserPojo> customerServices = userService.getCustomerServices();
        boolean serviceExists = customerServices.stream()
                .anyMatch(service -> service.getUserID().equals(customerServiceId));
        
        if (!serviceExists) {
            throw new RuntimeException("指定的客服不存在或不可用");
        }
        
        // 2. 检查是否有现有的活跃对话
        ConversationPojo existingConversation = getActiveConversationByCustomer(customerId);
        
        if (existingConversation != null) {
            // 3. 关闭旧对话并删除聊天记录
            closeConversationAndDeleteMessages(existingConversation.getConversationId());
        }
        
        // 4. 创建新对话
        ConversationPojo conversation = new ConversationPojo();
        conversation.setCustomerId(customerId);
        conversation.setCustomerServiceId(customerServiceId);
        conversation.setStatus("active");
        
        conversationDao.insert(conversation);
        
        // 5. 创建通知给客服
        UserPojo customer = userService.getUserByUserID(customerId);
        String customerName = customer != null ? customer.getUserName() : "用户";
        notificationService.createNotification(
            customerServiceId,
            "customer_service",
            "conversation_started",
            conversation.getConversationId(),
            "发起了新的客服咨询",
            customerName
        );
        
        return conversation;
    }
    
    /**
     * 获取顾客的活跃对话
     */
    public ConversationPojo getActiveConversationByCustomer(String customerId) {
        QueryWrapper<ConversationPojo> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_id", customerId)
               .eq("status", "active");
        
        return conversationDao.selectOne(wrapper);
    }
    
    /**
     * 获取客服的所有活跃对话
     */
    public List<ConversationPojo> getActiveConversationsByService(String customerServiceId) {
        QueryWrapper<ConversationPojo> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_service_id", customerServiceId)
               .eq("status", "active")
               .orderByDesc("last_message_time");
        
        List<ConversationPojo> conversations = conversationDao.selectList(wrapper);
        
        // 填充显示信息
        for (ConversationPojo conversation : conversations) {
            UserPojo customer = userService.getUserByUserID(conversation.getCustomerId());
            if (customer != null) {
                conversation.setCustomerName(customer.getUserName());
            }
            
            // 获取最后一条消息，优先显示用户发送的消息
            QueryWrapper<ConsolePojo> messageWrapper = new QueryWrapper<>();
            messageWrapper.eq("conversation_id", conversation.getConversationId())
                         .orderByDesc("create_time")
                         .last("LIMIT 1");
            
            ConsolePojo lastMessage = consoleDao.selectOne(messageWrapper);
            if (lastMessage != null) {
                // 获取发送者信息来判断是否为用户消息
                UserPojo sender = userService.getUserByUserID(lastMessage.getSenderId());
                if (sender != null && "customer".equals(sender.getRole())) {
                    // 如果最后一条是用户消息，直接显示
                    conversation.setLastMessage(lastMessage.getContent());
                } else {
                    // 如果最后一条是客服消息，查找用户的最新消息
                    QueryWrapper<ConsolePojo> customerMessageWrapper = new QueryWrapper<>();
                    customerMessageWrapper.eq("conversation_id", conversation.getConversationId())
                                         .eq("sender_id", conversation.getCustomerId())
                                         .orderByDesc("create_time")
                                         .last("LIMIT 1");
                    
                    ConsolePojo customerLastMessage = consoleDao.selectOne(customerMessageWrapper);
                    if (customerLastMessage != null) {
                        conversation.setLastMessage(customerLastMessage.getContent());
                    } else {
                        conversation.setLastMessage("用户尚未发送消息");
                    }
                }
            } else {
                conversation.setLastMessage("暂无消息记录");
            }
        }
        
        return conversations;
    }
    
    /**
     * 关闭对话并删除聊天记录
     */
    @Transactional
    public void closeConversationAndDeleteMessages(String conversationId) {
        // 1. 删除所有相关的聊天记录
        QueryWrapper<ConsolePojo> messageWrapper = new QueryWrapper<>();
        messageWrapper.eq("conversation_id", conversationId);
        consoleDao.delete(messageWrapper);
        
        // 2. 删除对话记录
        conversationDao.deleteById(conversationId);
    }
    
    /**
     * 更新对话的最后消息时间
     */
    @Transactional
    public void updateLastMessageTime(String conversationId) {
        ConversationPojo conversation = conversationDao.selectById(conversationId);
        if (conversation != null) {
            conversation.setLastMessageTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            conversationDao.updateById(conversation);
        }
    }
    
    /**
     * 根据ID获取对话
     */
    public ConversationPojo getConversationById(String conversationId) {
        return conversationDao.selectById(conversationId);
    }
    
    /**
     * 检查顾客是否有活跃对话
     */
    public boolean hasActiveConversation(String customerId) {
        return getActiveConversationByCustomer(customerId) != null;
    }
    
    /**
     * 结束对话（不删除消息记录）
     */
    @Transactional
    public void closeConversation(String conversationId) {
        ConversationPojo conversation = conversationDao.selectById(conversationId);
        if (conversation != null) {
            conversation.setStatus("closed");
            conversationDao.updateById(conversation);
        }
    }
    
    /**
     * 增加未读消息计数
     */
    @Transactional
    public void incrementUnreadCount(String conversationId, boolean isFromCustomer) {
        ConversationPojo conversation = conversationDao.selectById(conversationId);
        if (conversation != null) {
            if (isFromCustomer) {
                // 用户发送消息，增加客服未读计数
                conversation.setServiceUnreadCount(conversation.getServiceUnreadCount() + 1);
            } else {
                // 客服发送消息，增加用户未读计数
                conversation.setCustomerUnreadCount(conversation.getCustomerUnreadCount() + 1);
            }
            conversationDao.updateById(conversation);
        }
    }
    
    /**
     * 清零未读消息计数
     */
    @Transactional
    public void clearUnreadCount(String conversationId, boolean isCustomer) {
        ConversationPojo conversation = conversationDao.selectById(conversationId);
        if (conversation != null) {
            if (isCustomer) {
                // 用户查看消息，清零用户未读计数
                conversation.setCustomerUnreadCount(0);
            } else {
                // 客服查看消息，清零客服未读计数
                conversation.setServiceUnreadCount(0);
            }
            conversationDao.updateById(conversation);
        }
    }
    
    /**
     * 获取用户的未读消息总数
     */
    public int getCustomerUnreadCount(String customerId) {
        ConversationPojo conversation = getActiveConversationByCustomer(customerId);
        return conversation != null ? conversation.getCustomerUnreadCount() : 0;
    }
    
    /**
     * 获取客服的未读消息总数
     */
    public int getServiceUnreadCount(String customerServiceId) {
        QueryWrapper<ConversationPojo> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_service_id", customerServiceId)
               .eq("status", "active");
        
        List<ConversationPojo> conversations = conversationDao.selectList(wrapper);
        return conversations.stream()
                .mapToInt(ConversationPojo::getServiceUnreadCount)
                .sum();
    }
} 